package com.cyz.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.admin.service.ButtonService;
import com.cyz.admin.vo.ButtonVo;
import com.cyz.common.bean.Button;
import com.cyz.common.dto.ButtonDto;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.mapper.ButtonMapper;
import com.cyz.common.mapper.ButtongroupMapper;
import com.cyz.common.utils.BeanCopyUtil;
import com.cyz.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 管理端免费课程按钮接口实现类
 */
@Service
@Transactional
public class ButtonServiceImpl extends ServiceImpl<ButtonMapper, Button>
    implements ButtonService {

    @Autowired
    private ButtonMapper buttonMapper;
    @Autowired
    private ButtongroupMapper buttongroupMapper;

    @Override
    public R queryFreeButtons() {
//        LambdaQueryWrapper<Button> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        //根据名字进行排序
//        lambdaQueryWrapper.orderByAsc(Button::getName);
//        //查询数据
//        List<Button> list = list(lambdaQueryWrapper);

        //查询数据
        //根据名字进行排序
        List<Button> list = buttonMapper.queryFreeButtons();
        List<ButtonVo> buttonVos = BeanCopyUtil.copyBeanList(list, ButtonVo.class);
        buttonVos.forEach(item ->{
            item.setTypeName(buttongroupMapper
                    .getGroupNameById(item.getType()));
        });

        return R.success(buttonVos);
    }

    @Override
    public R deleteFreeButtons(Integer[] ids) {
//        //删除数据
//        boolean flag = removeByIds(Arrays.asList(ids));

        //删除数据
        boolean flag = buttonMapper.removeByIds(ids);
        //错误判断
        if(flag){
            return queryFreeButtons();
        }
        return R.error(MyEnums.DELETE_FAIL);
    }

    @Override
    public R addFreeButton(ButtonDto buttonDto) {
        //dto转化
        Button button = BeanCopyUtil.copyBean(buttonDto, Button.class);
//        //保存数据
//        boolean flag = save(button);
        //保存数据
        boolean flag = buttonMapper.addFreeButton(button);
        //错误数据
        if(flag){
            return queryFreeButtons();
        }
        return R.error(MyEnums.ADD_FAIL);
    }

    @Override
    public R updateFreeButton(ButtonDto buttonDto) {

        //dto转化
        Button button = BeanCopyUtil.copyBean(buttonDto, Button.class);

//        //保存数据
//        boolean flag = updateById(button);

        System.out.println(button);

        //保存数据
        boolean flag = buttonMapper.updateFreeButton(button);

        //错误数据
        if(flag){
            return queryFreeButtons();
        }
        return R.error(MyEnums.UPDATE_FAIL);
    }
}




